<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useUserInfoStore } from '@/store/userInfo'
import { userAvatarUpdateService, getUserInfoByTokenService, userInfoUpdateService } from '@/api/user';
import { getCurrentInstance } from "vue"

// 获取全局注册的组件
const { proxy } = getCurrentInstance();

// 用户信息状态
const userInfoStore = useUserInfoStore();

const router = useRouter()
const route = useRoute()

// 用户头像相关
let avatarRef = ref({})
let avatarList = ref([])

// 用户信息表单
const userInfoformData = ref({})
const userInfoformDataRef = ref()
const rules = {
  nickname: [
    { required: true, message: "请输入用户昵称", trigger: 'blur' },
  ],
  sex: [
    { required: true, message: "请输入用户性别", trigger: 'blur' },
  ],
  // personDescription: [
  //   { required: true, message: "请输入个人描述", trigger: 'blur' },
  // ],
}

// 获取用户信息
const getUserInfo = async () => {
  let res = await getUserInfoByTokenService()
  console.log(res)
  userInfoformData.value = res.data
}
onMounted(() => {
  getUserInfo()
})

// 修改用户头像
const updateUserAvatar = async () => {
  const formData = new FormData();
  formData.append('file', avatarList.value[0].raw);  // 获取文件对象
  let result = await userAvatarUpdateService(formData)
  console.log("头像上传成功")
  console.log(result)
  // 表单回显
  userInfoformData.value.avatar = result.data

  // 修改pinia中的用户头像
  userInfoStore.userInfo.avatar = result.data

  // 清空数组
  avatarList.value = []
}

function handleImageChange(file, fileList) {
  console.log("文件选择变化,file")
  console.log(file)
  console.log("文件选择变化,fileList")
  console.log(fileList)

  // 文件选择变化时的处理
  avatarList.value = fileList;

  // 修改用户头像
  updateUserAvatar()
};
function imageSuccess() {
  console.log("头像上传成功")
  avatarList.value = []
}
function imageError() {
  console.log("头像上传失败")
  avatarList.value = []
}


// 修改用户信息
const updateUserInfo = () => {
  userInfoformDataRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    // 请求后端
    console.log("准备好的请求参数，处理后为：", userInfoformData.value)
    let result = await userInfoUpdateService(userInfoformData.value)
    console.log("结果", result.data)

    // 修改Store中信息
    userInfoStore.userInfo.nickname = userInfoformData.value.nickname


    // 弹窗提示“用户信息修改成功”
    proxy.Notification.success("用户信息修改成功")
  })
}

</script>

<template>
  <div class="setting-profile-view">
    <div class="nav-text"><span>个人资料</span></div>

    <div class="user-infos">
      <div class="info-form">
        <el-form :model="userInfoformData" :rules="rules" ref="userInfoformDataRef" label-width="auto">
          <el-form-item prop="avatar" label="用户头像" label-position="right">
            <!-- 用户头像 -->
            <el-upload ref="avatarRef" class="avatar-uploader" accept="image/jpg,image/png,image/jpeg"
              :auto-upload="false" action="#" :show-file-list="false" :on-change="handleImageChange"
              :file-list="avatarList" :limit="1" :on-success="imageSuccess" :on-error="imageError">
              <img v-if="userInfoformData.avatar" :src="userInfoformData.avatar" />
              <!-- <span v-else class="iconfont icon-add1"></span> -->
              <img v-else src="../../../assets/default_avatar.jpg" alt="">
            </el-upload>
          </el-form-item>
          <el-form-item prop="nickname" label="用户昵称" label-position="right">
            <el-input placeholder="请输入用户昵称" v-model="userInfoformData.nickname"></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别" label-position="right">
            <!-- <el-input placeholder="请选择用户性别" v-model="userInfoformData.sex"></el-input> -->
            <el-radio-group v-model="userInfoformData.sex">
              <el-radio :value="1">男</el-radio>
              <el-radio :value="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="personDescription" label="个人介绍" label-position="right">
            <el-input placeholder="您可以填写您的兴趣爱好，擅长领域等" v-model="userInfoformData.personDescription" type="textarea"
              :rows="5" :maxlength="150" resize="none" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item label=" " label-position="right">
            <el-button type="primary" @click="updateUserInfo">保存更改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.setting-profile-view .nav-text {
  color: #252933;
  font-size: 18px;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e6eb;
}

.setting-profile-view .user-infos {
  padding: 20px 20px 40px;
}

.setting-profile-view .user-infos .info-form {
  width: 600px;
}

.setting-profile-view .user-infos .info-form .avatar-uploader {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.setting-profile-view .user-infos .info-form .avatar-uploader img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: contain;
  box-shadow: 0 0 10px 2px rgba(0, 0, 0, .06);
  border: 2px solid #fff;
}

.setting-profile-view .user-infos .info-form .avatar-uploader :deep(.el-upload) {
  height: 100px;
}
</style>